﻿#include "timer.h"

using namespace as;
Timer::Timer(const Timer &t)
{
	isRun_ = t.isRun_.load();
}

Timer::Timer() :isRun_(true)
{

}

Timer::~Timer()
{

}

void Timer::Tick()
{
	if (isRun_ == false)
		return;

	{
		std::unique_lock<std::mutex> locker(mutex_);
		expired_cond_.wait(locker, [this] 
			{
				return tasks_.empty() == false || isRun_ == false;
			}
		);

		auto time_now = std::chrono::system_clock::now();
		auto duration_in_ms = std::chrono::duration_cast<std::chrono::milliseconds>(time_now.time_since_epoch());
		std::vector<Timer::TimerEvent> tmp;
		tmp.reserve(tasks_.size());
		for (auto &task : tasks_)
		{
			if (duration_in_ms.count() >= task.lastTimeout_)
			{
				task.task_();
			}
			else
			{
				tmp.push_back(task);
			}
		}
		tmp.swap(tasks_);
	}
}

void Timer::Stop()
{
	isRun_ = false;
	expired_cond_.notify_all();
}

